#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'进程间的通信'

from multiprocessing import Process, Queue
import os, time, random


# 写数据进程执行
def put(q):
    print('Process to write:%s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue' % value)
        q.put(value)
        time.sleep(random.random())  # random.random()生成一个在0-1之间的随机数


# 读数据进程执行
def get(q):
    print('Process to get:%s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue' % value)


if __name__ == '__main__':
    # 父进程创建Queue
    q = Queue()
    pw = Process(target=put, args=(q,))
    pr = Process(target=get, args=(q,))
    # 启动子进程写
    pw.start()
    # 启动子进程读
    pr.start()
    # 等待pw结束
    pw.join()
    # pr进程里是死循环，无法等待其结束，只能强行终止
    pr.terminate()
